<?php
declare (strict_types = 1);

namespace app\command;

use app\common\models\Community\CommunityRank;
use app\common\models\Community\Rank;
use app\common\models\Community\RankAward;
use app\common\models\Community\RankData as RankDataModel;
use app\common\models\Community\RankMember;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

class RankData extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('rank:data')
            ->setDescription('the rank:data command');
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    protected function execute(Input $input, Output $output)
    {
        $lastWeekStart = date('Y-m-d H:i:s', strtotime('last week Monday'));
        //$lastWeekEnd = date('Y-m-d', strtotime('last week Sunday'));
        $now = date('Y-m-d H:i:s');
        $where = [
            ['is_switch','=',1],
            ['status','=',1],
            ['deleted','=',0],
            ['start_time','<=',$now],
            ['end_time','>=',$now],
        ];
        $rank = \app\common\models\Community\Rank::getInstance()->where($where)->find();
        if(empty($rank)){
            return false;
        }

        $where = [
            ['is_switch','=',1],
            ['condition_type','=',1],
            ['status','=',1],
        ];
        $min = Rank::getInstance()->where($where)->value('condition_value') ?: 0;
        $where = [
            ['c.start_time','=',$lastWeekStart],
            ['c.num','>=',$min]
        ];
        $userIds = RankMember::getInstance()->where('deleted',0)->column('user_id');
        if(!empty($userIds)){
            $where[] = ['m.id','not in',$userIds];
        }
        $infoSql = CommunityRank::getInstance()
            ->alias('c')
            ->leftJoin('member m','c.user_id=m.id')
            ->field('c.user_id,m.phone,m.user_name,m.avatar,c.num')
            ->where($where)
            ->order('c.num desc')
            ->buildSql();
        Db::execute('SET @rank= 0;');
        $rankSql = Db::table($infoSql . ' g')
            ->field('(@rank:=@rank + 1) AS rank,g.*')
            ->buildSql();
        //列表数据
        $list = Db::table($rankSql . ' r')->select();
        $where = [
            ['deleted','=',0],
            ['rank_id','=',$rank['id']]
        ];
        $awardList = RankAward::getInstance()->where($where)->select();
        if(empty($awardList)){
            return false;
        }
        foreach($list as $v){
            foreach ($awardList as $vv){
                //单次排名
                if($vv['type'] == 0){
                    if($v['rank'] != $vv['single']){
                       continue;
                    }
                }else{
                    if($v['rank'] < $vv['rangeStart'] || $v['rank'] > $vv['rangeEnd']){
                        continue;
                    }
                }
                $this->insertData($v['rank'], $v['user_id'], $v['phone'], $rank['id'], $lastWeekStart, $vv);
            }
        }
        // 指令输出
        $output->writeln('rank:data');
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function insertData($num, $userId, $phone, $rankId, $lastWeekStart, $randAward): bool
    {
        $where = [
            ['rank_id','=',$rankId],
            ['user_id','=',$userId],
            ['last_week_start','=',$lastWeekStart],
        ];
        $rankData = RankDataModel::getInstance()->where($where)->find();
        if(!empty($rankData)){
            $rankData->update_at = date('Y-m-d H:i:s');
            $rankData->save();
        }else{
            $data = [
                'award_type' => $randAward['awardType'],
                'user_id' => $userId,
                'phone' => $phone,
                'rank_id' => $rankId,
                'gxz' => $randAward['gxz'],
                'balance' => $randAward['balance'],
                'rank_award_id' => $randAward['id'],
                'title' => '第'.$num.'名',
                'last_week_start' => $lastWeekStart,
            ];
            RankDataModel::getInstance()->insert($data);
        }
        return true;
    }
}
